using System;

namespace SharpMud.MudLib.SAMPLE.Net.SessionStates
{
	public class Logon : SessionStateBase
	{
		public override string StateID
		{
			get
			{
				return "Logon";
			}
		}

		public override void Pulse()
		{
			string sName = Session.Prompt("By what name are you known here? ").Trim();
#if Use_Common_MudLib
            while(sName==String.Empty || !MudServer.PlayerManager.IsValidPlayerName(sName))
#else
            while(sName==String.Empty || !MudServer.PlayerSystem.IsValidName(sName))
#endif
            {
				Session.WriteLine();
				if(sName==String.Empty)
				{
					Session.WriteLine("Surely you have a name.");
					sName = Session.Prompt("By what name are you known here? ").Trim();
				}
#if Use_Common_MudLib
                if (!MudServer.PlayerManager.IsValidPlayerName(sName)) ;
#else
                if(!MudServer.PlayerSystem.IsValidName(sName))
#endif
                {
					Session.WriteLine("That is surely not your name.");
					sName = Session.Prompt("What is your name? ").Trim();	
				}
			}
#if Use_Common_MudLib
            if(!MudServer.PlayerManager.PlayerExists(sName))
#else
			if(!MudServer.PlayerSystem.Players.PlayerExists(sName))
#endif
			{
				//Player doesn't exist.
				//Verify name, and then begin character creation
				Session.WriteLine("Apparently you don't exist.");
				string answer = Session.Prompt("Do you wish to be called '{0}'? ",sName).Trim();
				while(true)
				{
					if("yes".StartsWith(answer.ToLower()))
					{
						break;
					}
					else if("no".StartsWith(answer.ToLower()))
					{
						//TODO: Clear screen here
						for(int x=0;x<30;x++)
							Session.WriteLine();
						return;
					}
					else
					{	
						answer = Session.Prompt("Well? Do you want to be called '{0}', yes or no? ",sName).Trim();
						continue;
					}
				}
				Session.SessionState.Push(new PlayerCreation.StartCreation(sName));
				this.SetInactive();
				return;
			}
			else
			{
				//Player exists...proceed with logon
				Session.WriteLine();
				Session.Agents.RemoteEcho.TurnFeatureOff();
				string sPassword = Session.Prompt("Please type your password: ");
				Session.Agents.RemoteEcho.TurnFeatureOn();
				Session.WriteLine();
				
				Session.WriteLine();
				try
				{
					Session.Logon(sName,sPassword);
				}
				catch(SharpMud.MudLib.SAMPLE.Entities.PasswordMismatchException e)
				{
					Session.Log.Info("Password mismatch for player '" + e.PlayerName + "'");
					Session.WriteLine("Invalid password!");
					Session.WriteLine();
					Session.WriteLine("Goodbye!");
					this.SetInactive();
					return;
				}
				this.SetInactive();
				this.Session.SessionState.Clear();
				Session.SessionState.Push(new SessionStates.PutInWorld());
				return;
			}
		}
		
		public SharpMud.MudLib.SAMPLE.MudLibRoot MudServer
		{
			get
			{
				return (SharpMud.MudLib.SAMPLE.MudLibRoot)Session.Host.Host;
			}
		}
	}
}
